package com.cmb.lk50.sink.mongo;

import com.cmb.lk50.config.LogInProperties;
import com.cmb.lk50.pojo.AbstractLog;
import com.cmb.lk50.sink.AsyncLogSink;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;

/**
 * Author       : 蒋俊钊 80256973
 * Date         : 2020/7/20
 * Copyright    (C) ChinaMerchantsBank
 */
public class MongoSink<T extends AbstractLog> extends AsyncLogSink {

    private static final Logger LOGGER = LoggerFactory.getLogger(MongoSink.class);

    private MongoDatabase db;

    private String collectionName;

    public MongoSink(MongoClient client, LogInProperties.MongodbProperties properties, ExecutorService asyncExecutor) {
        super(asyncExecutor);
        this.db = client.getDatabase(properties.getDatabase());
        this.collectionName = properties.getDefaultCollection();
    }

    @Override
    protected void asyncWrite(AbstractLog log) {
        MongoCollection<T> collection = (MongoCollection<T>) db.getCollection(log.mongoCollection() == null ? collectionName : log.mongoCollection(), log.getClass());

        try {
            collection.insertOne((T) log);
        } catch (RuntimeException e) {
            LOGGER.debug("日志写入mongodb异常, [{}]", e.getMessage());
        }
    }

}
